﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using Lib.Approval;
using Lib.Helper;
using Lib.Mail;
using MSIACCSL2.Command;
using MSIACCSL2.GroupServices;
using MSIACCSL2.SubGroupServices;
using MSIACCSL2.Views.SubGroup;
using WcfService1.DTO;
using DeleteCompletedEventArgs = MSIACCSL2.SubGroupServices.DeleteCompletedEventArgs;
using GetListByCriteriaCompletedEventArgs = MSIACCSL2.SubGroupServices.GetListByCriteriaCompletedEventArgs;
using GetListCompletedEventArgs = MSIACCSL2.SubGroupServices.GetListCompletedEventArgs;
using Group = WcfService1.DTO.GroupDTO;
using SaveCompletedEventArgs = MSIACCSL2.SubGroupServices.SaveCompletedEventArgs;
using SubGroup = WcfService1.DTO.SubGroupDTO;

namespace MSIACCSL2.ViewModels
{
    public class SubGroupViewModel : ViewModelBase
    {
        #region Delegates

        public delegate void Completed(Object param);

        #endregion

        private static string OrderType;
        private static string PropertySort;
        public static Mode mode;
        private static SubGroup _group;
        private static Add frmAdd;
        public static Completed OnSearchCompleted;
        private static Search frmSearch;
        private readonly GroupServicesClient GroupClient;
        private readonly SubGroupServiceClient client;
        private readonly ValidationHandler validationHandler;
        private int CurrentPage;
        private ObservableCollection<int> Pages;
        private bool _IsBusy;
        private ObservableCollection<Group> _groups;
        private PagedCollectionView _pageSources;
        private PagedCollectionView _subGroups;
        private Dictionary<string, object> criteria;
        private string expression;


        public SubGroupViewModel()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                client = new SubGroupServiceClient();
                GroupClient = new GroupServicesClient();
                OnPageChanged = new DelegateCommand(PageIndexChanged, CanPageIndexChanged);
                Save = new DelegateCommand(SaveSubGroup, CanSave);
                New = new DelegateCommand(NewSubGroup, CanNew);
                Edit = new DelegateCommand(EditSubGroup, CanEdit);
                Unload = new DelegateCommand(Release, CanUnload);
                SearchCommand = new DelegateCommand(SearchSubGroup, CanSearch);
                SearchResultCommand = new DelegateCommand(SearchResult, CanSearchResult);
                validationHandler = new ValidationHandler();

                //Kalo lagi di Edit jangan diload Datanya tar nimpa

                if (mode == Mode.Edit || mode == Mode.Search || mode == Mode.Add)
                {
                    GetGroupList();
                }
                else
                {
                    GetList(1, null);
                }
            }
        }

        public PagedCollectionView SubGroups
        {
            get { return _subGroups; }

            private set
            {
                if (SubGroups == value) return;
                _subGroups = value;

                int i = (CurrentPage*30);
                foreach (object subGroup in SubGroups)
                {
                    i += 1;

                    ((SubGroup) subGroup).No = i;
                }

                FirePropertyChanged("SubGroups");
                SubGroups.CollectionChanged += Group_CollectionChanged;
            }
        }


        public PagedCollectionView PageSources
        {
            get { return _pageSources; }
            private set
            {
                if (PageSources == value) return;
                _pageSources = value;
                FirePropertyChanged("PageSources");
            }
        }


        public ObservableCollection<Group> Groups
        {
            get { return _groups; }
            private set
            {
                if (Groups == value) return;
                _groups = value;
                FirePropertyChanged("Groups");
            }
        }


        public bool IsBusy
        {
            get { return _IsBusy; }
            internal set
            {
                _IsBusy = value;
                FirePropertyChanged("IsBusy");
            }
        }

        public long RecordCount { get; set; }

        //Buat binding ke child form waktu mau edit
        public static SubGroup SubGroup
        {
            get { return _group; }
            private set
            {
                if (SubGroup == value) return;
                _group = value;
                FirePropertyChanged2("SubGroup");
            }
        }


        public ICommand OnPageChanged { get; set; }
        public ICommand Save { get; set; }
        public ICommand New { get; set; }
        public ICommand Edit { get; set; }
        public ICommand Unload { get; set; }
        public ICommand SearchCommand { get; set; }
        public ICommand SearchResultCommand { get; set; }

        public string Error
        {
            get { return null; }
        }

        public string this[string columnName]
        {
            get
            {
                if (validationHandler.BrokenRuleExists(columnName))
                {
                    return validationHandler[columnName];
                }
                return null;
            }
        }

        public void Complete(Object param)
        {
            OnSearchCompleted(param);
        }

        private void Group_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (((PagedCollectionView) sender).SortDescriptions.Count > 0)
            {
                if (((PagedCollectionView) sender).SortDescriptions[0].PropertyName.ToLower() == "no") return;

                PropertySort = ((PagedCollectionView) sender).SortDescriptions[0].PropertyName;
                if (string.IsNullOrEmpty(OrderType))
                {
                    OrderType = "ASC";
                }
                else
                {
                    OrderType = OrderType == "ASC" ? OrderType = "DESC" : OrderType = "ASC";
                }
                GetList(1, PropertySort);
            }
        }


        public void SaveSubGroup(Object subGroup)
        {
            ((SubGroup) subGroup).created_by = GlobalVar.User.UserID;
            ((SubGroup) subGroup).modified_by = GlobalVar.User.UserID;
            client.SaveCompleted += client_SaveCompleted;
            client.SaveAsync((SubGroup) subGroup);
        }

        private void client_SaveCompleted(object sender, SaveCompletedEventArgs e)
        {
            client.SaveCompleted -= client_SaveCompleted;
            if (e.Result)
            {
                MessageBox.Show("Success");
                frmAdd.DialogResult = true;
                Refresh();
            }
        }


        public void GetList(int? page, string sortProp)
        {
            IsBusy = true;
            client.GetListCompleted += client_GetListCompleted;
            client.GetListAsync(page ?? 1, sortProp, OrderType);
        }

        private void client_GetListCompleted(object sender, GetListCompletedEventArgs e)
        {
            RecordCount = e.recordCount;
            if (PageSources == null) CreatePageNumber();
            client.GetListCompleted -= client_GetListCompleted;
            SubGroups = new PagedCollectionView(e.Result);
            IsBusy = false;
            Complete(this);
        }


        private void NewSubGroup(Object param)
        {
            mode = Mode.Add;
            SubGroup = new SubGroup();
            frmAdd = new Add();
            frmAdd.Show();
        }


        public static void EditSubGroup(Object param)
        {
            mode = Mode.Edit;
            SubGroup = (SubGroup) param;
            frmAdd = new Add();
            frmAdd.Show();
        }


        private void SearchSubGroup(Object param)
        {
            mode = Mode.Search;
            SubGroup = new SubGroup();
            frmSearch = new Search();
            frmSearch.Show();
        }


        private void SearchResult(Object param)
        {
            SubGroup = (SubGroup) param;
            criteria = new Dictionary<string, object>();

            foreach (PropertyInfo prop in SubGroup.GetType().GetProperties())
            {
                if (prop.PropertyType == typeof (Decimal))
                {
                    if ((Decimal) prop.GetValue(SubGroup, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Int32))
                {
                    if ((Int32) prop.GetValue(SubGroup, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Int64))
                {
                    if ((Int64) prop.GetValue(SubGroup, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Double))
                {
                    if ((Double) prop.GetValue(SubGroup, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (String))
                {
                    if (String.IsNullOrEmpty((String) prop.GetValue(SubGroup, null))) continue;
                }
                if (prop.PropertyType == typeof (DateTime))
                {
                    if (prop.GetValue(SubGroup, null).ToString().Contains("0001")) continue;
                }
                if (prop.GetValue(SubGroup, null) == null) continue;
                if (prop.PropertyType.Name == "No") continue;

                if (prop.PropertyType.Name.ToLower().Contains("dto"))
                {
                    foreach (PropertyInfo propertyInfo in prop.GetValue(SubGroup, null).GetType().GetProperties()
                        )
                    {
                        if (propertyInfo.Name.ToLower().Contains("id") || propertyInfo.Name.ToLower().Contains("kode") ||
                            propertyInfo.Name.ToLower().Contains("serial") ||
                            propertyInfo.Name.ToLower().Contains("code"))
                        {
                            criteria.Add(prop.Name, propertyInfo.GetValue(prop.GetValue(SubGroup, null), null));
                            break;
                        }
                    }
                }
                else
                {
                    criteria.Add(prop.Name, prop.GetValue(SubGroup, null));
                }
            }

            string expression = string.Empty;
            if (frmSearch.rblOr.IsChecked ?? false) expression = "OR";
            expression = "AND";
            SubGroupSearch(criteria, expression,1);
        }

        private void SubGroupSearch(Dictionary<String, Object> criteria, string expression,int page)
        {
            frmSearch.DialogResult = true;
            IsBusy = true;
            Complete(this);
            client.GetListByCriteriaCompleted += client_GetListByCriteriaCompleted;
            client.GetListByCriteriaAsync(criteria, expression, page);
        }

        private void client_GetListByCriteriaCompleted(object sender, GetListByCriteriaCompletedEventArgs e)
        {
            SubGroups = new PagedCollectionView(e.Result);
            if (RecordCount != e.recordCount)
            {
                RecordCount = e.recordCount;
                CreatePageNumber();
            }
            IsBusy = false;
        }

        private void GetGroupList()
        {
            GroupClient.GetListCompleted += GroupClient_GetListCompleted;
            GroupClient.GetListAsync(1, null, null);
        }

        private void GroupClient_GetListCompleted(object sender, GroupServices.GetListCompletedEventArgs e)
        {
            Groups = new ObservableCollection<Group>((from g in e.Result
                                                      select
                                                          new Group
                                                              {
                                                                  Description = g.Description,
                                                                  GroupID = g.GroupID,
                                                                  GroupName = g.GroupName
                                                              }));
            if (mode == Mode.Edit)
            {
                if (SubGroup.Group == null) return;
                SubGroup.Group = Groups.FirstOrDefault(g => g.GroupID == SubGroup.Group.GroupID);
            }
        }

        public void GetSubGroupByName(Object param)
        {
            client.GetSubGroupListByNameCompleted += client_GetSubGroupListByNameCompleted;
            client.GetSubGroupListByNameAsync(param.ToString());
        }

        private void client_GetSubGroupListByNameCompleted(object sender, GetSubGroupListByNameCompletedEventArgs e)
        {
            client.GetSubGroupListByNameCompleted -= client_GetSubGroupListByNameCompleted;
            SubGroups = new PagedCollectionView(e.Result);
        }

        private void CreatePageNumber()
        {
            Pages = new ObservableCollection<int>();
            for (int i = 0; i < RecordCount; i++)
            {
                Pages.Add(i);
            }
            PageSources = new PagedCollectionView(Pages);
        }


        private void PageIndexChanged(Object pageIndex)
        {
            //Jika Pertama kali jangan di Getlagi
            SubGroup = null;
            if (SubGroups != null && CurrentPage != (int) pageIndex)
            {
                CurrentPage = (int) pageIndex;
                if (mode == Mode.Search)
                    SubGroupSearch(criteria, expression, (int)pageIndex + 1);
                else if (String.IsNullOrEmpty(PropertySort))
                    GetList((int) pageIndex + 1, null);
                else GetList((int) pageIndex + 1, PropertySort);
            }
        }


        public bool CanPageIndexChanged(Object param)
        {
            return true;
        }


        public bool CanSave(Object param)
        {
            return true;
        }


        public bool CanNew(Object param)
        {
            return true;
        }

        public bool CanEdit(Object param)
        {
            return true;
        }


        public bool CanUnload(Object param)
        {
            return true;
        }


        public bool CanSearch(Object param)
        {
            return true;
        }

        public bool CanSearchResult(Object param)
        {
            return true;
        }


        public void Release(Object param)
        {
            param = null;
            SubGroup = null;
            OrderType = null;
            PropertySort = null;
            mode = Mode.Idle;
        }


        public void Refresh()
        {
            if (SubGroups == null)
                GetList(1, null);
            else
                Complete(this);
        }


        public void SendEmail(Object param)
        {
            ChooseDestination chooseDestination = new ChooseDestination();
            chooseDestination.Show();
            EventAggregator.RegisterMessage("SendDestination", (x) =>
            {
                IsBusy = true;
                client.SendEmailCompleted += client_SendEmailCompleted;
                client.SendEmailAsync(param as SubGroup, (x as WarehouseDTO).EmailFolder);
            });
        }

        private void client_SendEmailCompleted(object sender, SubGroupServices.SendEmailCompletedEventArgs e)
        {
            IsBusy = false;
            client.SendEmailCompleted -= client_SendEmailCompleted;
            if (e.Result) MessageBox.Show("Pengiriman Selesai");
        }
    }


    public class SubGroupWrapViewModel : ViewModelBase
    {
        private readonly SubGroupServiceClient client;

        public SubGroupWrapViewModel()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                EditCommand = new DelegateCommand(Edit, CanEditCommand);
                DeleteCommand = new DelegateCommand(Delete, CanDeleteCommand);
                client = new SubGroupServiceClient();
            }
        }

        public SubGroup SubGroup { get; set; }
        public ICommand EditCommand { get; set; }
        public ICommand DeleteCommand { get; set; }


        public bool CanEditCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteCommand(Object param)
        {
            return true;
        }


        public void Edit(Object param)
        {
            SubGroupViewModel.EditSubGroup(param);
        }

        public void Delete(Object param)
        {
            DeleteConfirmation deleteConfirmation = new DeleteConfirmation();
            deleteConfirmation.Show();
            EventAggregator.RegisterMessage("ApprovalSucceeded", (x) =>
            {
                deleteConfirmation.Close();
                client.DeleteCompleted += client_DeleteCompleted;
                client.DeleteAsync((SubGroup)param);
            });
        }

        private void client_DeleteCompleted(object sender, DeleteCompletedEventArgs e)
        {
            client.DeleteCompleted -= client_DeleteCompleted;
            if (e.Result)
            {
                MessageBox.Show("Delete Success!");
            }
            else
            {
                MessageBox.Show("Data sudah link ke transaksi lain, tidak boleh dihapus!");
            }
            SubGroupViewModel.mode = Mode.Idle;
            var VM = new SubGroupViewModel();
        }
    }


    public class GroupConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                return ((dynamic) value).GroupName;
            }
            else
            {
                return string.Empty;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}